#!/bin/bash
# 此脚本用来编译安装fsl-6.0.5.2软件
# fsl-6.0.5.2软件介绍
#  FSL 是一个全面的分析工具库，用于 FMRI、MRI 和 DTI 脑成像数据。
#  Usage:
#     bash /path/to/build.sh /path/to/build /path/to/install
# 使用build.sh 脚本样例 bash /path/to/build.sh /path/to/build /path/to/install
# 使用build.sh 需要root权限或者sudo权限,否则无法安装依赖
#
##############################################################

source "$(
  cd "$(dirname "$0")" || exit 1
  pwd
)/common.sh"

function install_development() {
  sudo yum install -y m4 bc zlib-devel zlib environment-modules systemd-devel
  source /etc/profile
  module purge
}

function install_bisheng() {
  bash "$1"/bisheng-compiler-2.1.0.sh "$2" "$3"
  module use "$3"/bisheng-compiler-2.1.0
  module load "$3"/bisheng-compiler-2.1.0/bisheng_modulefiles
}

function install_fsl() {
  bash "$4"/fsl-6.0.5.2.sh "$1" "$2"
  mkdir -p "$3"/fsl-6.0.5.2-hpc && cp -r "$2"/* "$3"/fsl-6.0.5.2-hpc/
}


function write_fsl_run() {
  cat >"$1/fsl-6.0.5.2-hpc/run.sh" <<EOF
#!/bin/bash

yum install -y wget tar libatomic environment-modules patch Cython cmake \\
  git expat-devel libX11-devel mesa-libGL-devel zlib zlib-devel gd gd-devel \\
  libxml* libopenblas*

source /etc/profile &>/dev/null

export FSLDIR=\$(pwd)/fsl-6.0.5.2
. \$FSLDIR/etc/fslconf/fsl.sh
bash \$FSLDIR/etc/fslconf/post_install.sh -f \$FSLDIR

current_dir="\$(cd "\$(dirname "\${BASH_SOURCE[0]}")" && pwd -P)"
for f in "\${current_dir}"/*; do
  if [[ -d "\${f}" && -f "\$(ls "\${f}"/*modulefiles 2>&1)" ]]; then
    module use "\${f}" && module load "\${f}"/*modulefiles
  fi
done

echo -e "\033[1;32;1mfsl environment initialization completed.\033[0m"

EOF

  chmod +x "$1"/fsl-6.0.5.2-hpc/run.sh
}

function tar_pkg() {
  echo "# 正在打包 fsl 文件 路径为$1"
  cd "$1" && tar -zcf fsl-6.0.5.2-hpc.tar.gz fsl-6.0.5.2-hpc
  echo -e "\033[1;32;1m# fsl 已经打包成功 文件路径为$1/fsl-6.0.5.2-hpc.tar.gz\033[0m"
}

function main() {
  set_script_dir

  # $1（构建路径）、$2（安装路径）检测
  is_check_build_install_directory "$1" "$2" "build.sh"

  # 构建路径
  buildpath=$(create_dir "$1")

  # 安装路径
  installpath=$(create_dir "$2")

  # 依赖路径
  dep_dir="${SCRIPT_DIR}"/dependency

  # 打包路径
  pkg_dir="${SCRIPT_DIR}"/pkg

  install_development
  install_bisheng "$dep_dir" "$buildpath" "$installpath"
  install_fsl "$buildpath" "$installpath" "$pkg_dir" "${SCRIPT_DIR}"
  set -e
  write_fsl_run "$pkg_dir"
  tar_pkg "$pkg_dir"
  echo " # ------------------------------------------------------------------------"
  echo "# 运行软件前请执行以下命令"
  echo -e "\033[1;32;1m# source ""${pkg_dir}""/fsl-6.0.5.2-hpc/run.sh\033[0m"
  echo "# 来加载 fsl 运行时环境变量"
  echo "# ------------------------------------------------------------------------"
  rm -rf "$buildpath" "$installpath"
}

main "$@"
